package com.ytu.clouddisk.face;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.ParseException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnKeyListener;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.ytu.clouddis.google.DocsControl;
import com.ytu.clouddisk.face.CloudDiskLoginActivity.LoginThread;
import com.ytu.clouddisk.kanbox.KanBoxControl;
import com.ytu.clouddisk.sdcard.SDCard;
import com.ytu.clouddisk.utils.CommonUtil;
import com.ytu.clouddisk.utils.LoginUtil;
import com.ytu.clouddisk.utils.Varibles;
import com.ytu.clouddisk.vdisk.VDiskControl;
import android.widget.Toast;

public class BrowserActivity extends Activity {

	private SharedPreferences pref;
	private static ProgressDialog dlg_wait;
	MenuItemData mMenuItemData1;
	MenuItemData mMenuItemData2;
	private boolean mIsMore = true; // 弹出菜单翻页控制

	private GridView mMenuGrid; // 弹出菜单GRIDVIEW
	private View mMenuView; // 弹出菜单视图
	private GVAdapter mGridViewAdapter; // 弹出菜单适配器
	private PopupWindow mPopupWindow; // 弹出菜单WINDOW

	private MenuItemData mToolBarItemData;
	private GridView mToolBarGrid; // 底部菜单栏
	private GVAdapter mToolBarAdapter; // 底部菜单栏适配器
	private LVAdapter mListViewAdapter; // 界面显示存储卡所含文件适配器
	private static ListView mListView; // listview填充
	private ListViewItemData mListViewItemData;
	private int selectToolItem = 0;
	private static SDCard sdCard;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.file_explorer);
		setTitle("ControlPad");
		if (existSDcard())
			sdCard = SDCard.getInstance();
		else
			finish();
		initListView();
		initToolbarMenu();
		initPopMenu();
		pref = getSharedPreferences(Varibles.CONFIG_FILE, MODE_PRIVATE);
		initLogin();

		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adpater, View arg1,
					int arg2, long arg3) {
				switch (Varibles.CURRENT_TOOLBAR_ITEM) {
				case 0: {
					// 文件夹的浏览 先判断是否是上一级 每次点击先换当前目录
					String select = ((LVAdapter) mListView.getAdapter()).mListViewItemData
							.getTitle(arg2);
					if (select.equals("上一级")) {
						File[] f = sdCard.upLevel(); // 已经改变当前目录
						refreshListView(sdCard.getFilesName(f));

					} else {
						// 拼接目录
						String addr = sdCard.getCurrentDir() + "/" + select;
						// 改变当前目录
						if (sdCard.browseFile(addr) != null) {
							sdCard.setCurrentDir(addr);
							refreshListView(sdCard.getFilesName(sdCard
									.browseFile(addr)));
						} else {
							// Toast.makeText(BrowserActivity.this, "无法访问",
							// Toast.LENGTH_SHORT).show();
							// 判断文件后缀名 上传文件
							String type = CommonUtil.checkType(
									BrowserActivity.this, select);
							try {
								VDiskControl.upload(pref.getString(
										Varibles.VDISK_TOKEN, null), select,
										addr, type);
							} catch (ParseException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
					// Log.e("当前路径：", sdCard.getCurrentDir());
					break;
				}
				case 1:
					// 下载
					break;
				case 2:
					// 下载
					break;
				case 3:
					// 下载
					break;
				}
			}
		});
	}

	/**
	 * 初始登陆 获取Token
	 */
	private void initLogin() {

	}

	/**
	 * 初始化列表
	 */
	private void initListView() {
		refreshListView(sdCard.getFilesName(sdCard.browseSDCard()));
	}

	/**
	 * 刷新列表
	 * 
	 * @param list
	 */
	private void refreshListView(List<String> list) {
		/* 获取文件名数组 */
		List<String> file_name_array = new ArrayList<String>();
		if (!existSDcard())
			file_name_array.add("Not exist SDCard.");
		else {
			file_name_array = list;
		}
		LevelListDrawable levelListDrawable = (LevelListDrawable) getResources()
				.getDrawable(R.drawable.listview_image_file); // 获取图片列表
		mListViewItemData = new ListViewItemData(levelListDrawable,
				file_name_array, file_name_array.size());

		mListView = (ListView) findViewById(R.id.ListView);
		mListViewAdapter = new LVAdapter(this, mListViewItemData);
		mListView.setAdapter(mListViewAdapter);
		mListView.setCacheColorHint(0x0000000F); // 设置拖动时保存背景色

	}

	/**
	 * 判断是否存在存储卡
	 */
	public static boolean existSDcard() {
		if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
				.getExternalStorageState())) {
			return true;
		} else
			return false;
	}

	/**
	 * 获取listview
	 */
	public static ListView getListView() {
		if (mListView != null)
			return mListView;
		else
			return null;
	}

	/**
	 * 初始化弹出菜单
	 */
	private void initPopMenu() {
		// 第一个菜单
		String[] menu_name_array1 = getResources().getStringArray(
				R.array.menu_item_name_array1); // 获取菜单项的文字
		LevelListDrawable levelListDrawable1 = (LevelListDrawable) getResources()
				.getDrawable(R.drawable.menu_image_list1);// 获取菜单项的图片
		mMenuItemData1 = new MenuItemData(levelListDrawable1, menu_name_array1,
				menu_name_array1.length); // 菜单项对象化
		// 第二个菜单
		String[] menu_name_array2 = getResources().getStringArray(
				R.array.menu_item_name_array2);
		LevelListDrawable levelListDrawable2 = (LevelListDrawable) getResources()
				.getDrawable(R.drawable.menu_image_list2);
		mMenuItemData2 = new MenuItemData(levelListDrawable2, menu_name_array2,
				menu_name_array2.length);

		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mMenuView = inflater.inflate(R.layout.menu, null);
		mMenuGrid = (GridView) mMenuView.findViewById(R.id.menuGridChange); // get

		mGridViewAdapter = new GVAdapter(this, mMenuItemData1);
		mMenuGrid.setAdapter(mGridViewAdapter);
		mMenuGrid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				switch (position) {
				case 0:
					setTitle("00");
					break;
				case 1:
					setTitle("111");
					break;
				case 2:
					break;
				case 8:
					finish();
				default:
					break;
				}
			}
		});

		mMenuGrid.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				switch (keyCode) {
				case KeyEvent.KEYCODE_MENU:
					showMenuWindow();
					break;
				}
				return false;
			}
		});

		mPopupWindow = new PopupWindow(mMenuView, LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		mPopupWindow.setFocusable(true); // 如果没有获得焦点menu菜单中的控件事件无法响应

		// 以下两行加上去后就可以使用BACK键关闭POPWINDOW
		ColorDrawable dw = new ColorDrawable(0xb0000000);
		mPopupWindow.setBackgroundDrawable(dw);
		mPopupWindow.setAnimationStyle(android.R.style.Animation_Toast);
	}

	/**
	 * 工具栏初始化
	 */

	Handler getFileListHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			dlg_wait.dismiss();
		}
	};

	private void initToolbarMenu() {
		String[] toolbar_name_array = getResources().getStringArray(
				R.array.toolbar_name_array_cn);
		LevelListDrawable levelListDrawable = (LevelListDrawable) getResources()
				.getDrawable(R.drawable.toolbar_image_list);
		mToolBarItemData = new MenuItemData(levelListDrawable,
				toolbar_name_array, toolbar_name_array.length);

		mToolBarGrid = (GridView) findViewById(R.id.GridView_toolbar);
		mToolBarAdapter = new GVAdapter(this, mToolBarItemData);
		mToolBarGrid.setAdapter(mToolBarAdapter);
		mToolBarGrid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				switch (position) {
				case 0:
					initListView();
					sdCard.setCurrentDir(Environment
							.getExternalStorageDirectory().getAbsolutePath());
					Varibles.CURRENT_TOOLBAR_ITEM = 0;
					break;
				case 1:
					// 获取Google文档列表并刷新listview
					if (!getSharedPreferences(Varibles.CONFIG_FILE,
							MODE_PRIVATE).contains(Varibles.GOOGLE_TOKEN)) {
						Toast.makeText(BrowserActivity.this, "请先登录",
								Toast.LENGTH_SHORT).show();
						return;
					} else {
						// dlg_wait = ProgressDialog.show(BrowserActivity.this,
						// "Please waiting...", "Docs 列表获取中...", true);
						Varibles.CURRENT_TOOLBAR_ITEM = 1;
						DocsControl.getInstance(BrowserActivity.this)
								.executeRefreshDocs();
						// new BackgroundThread(Varibles.GOOGLEDOCS).start();
					}
					break;
				case 2:
					// 获取KanBox列表
					if (!getSharedPreferences(Varibles.CONFIG_FILE,
							MODE_PRIVATE)
							.contains(Varibles.KANBOX_ACCESS_TOKEN)) {
						Toast.makeText(BrowserActivity.this, "请先登录",
								Toast.LENGTH_SHORT).show();
						return;
					} else {
						dlg_wait = ProgressDialog.show(BrowserActivity.this,
								"Please waiting...", "酷盘列表获取中...", true);
						Varibles.CURRENT_TOOLBAR_ITEM = 2;
						new BackgroundThread(Varibles.VDISK).start();
					}
					break;
				case 3:
					// 获取VDisk列表
					if (!getSharedPreferences(Varibles.CONFIG_FILE,
							MODE_PRIVATE).contains(Varibles.VDISK_TOKEN)) {
						Toast.makeText(BrowserActivity.this, "请先登录",
								Toast.LENGTH_SHORT).show();
						return;
					} else {
						dlg_wait = ProgressDialog.show(BrowserActivity.this,
								"Please waiting...", "微盘列表获取中...", true);
						Varibles.CURRENT_TOOLBAR_ITEM = 3;
						// new BackgroundThread(Varibles.VDISK).start();
						Thread background = new Thread(new Runnable() {
							@Override
							public void run() {
								try {
									test();
								} catch (Exception e) {

								} finally {
									getFileListHandler.sendEmptyMessage(0);
								}
							}
						});
						background.start();
					}
					break;
				case 4:
					Varibles.CURRENT_TOOLBAR_ITEM = 4;
					showMenuWindow();
					break;
				default:
					break;
				}
			}
		});
		mToolBarGrid.setSelection(Varibles.SDCARD);
	}

	private void test() {
		VDiskControl.getList(BrowserActivity.this,
				getSharedPreferences(Varibles.CONFIG_FILE, MODE_PRIVATE)
						.getString(Varibles.VDISK_TOKEN, null));
		setTitle("aaaaaaaaaa");
		Toast.makeText(BrowserActivity.this, "dadad", Toast.LENGTH_SHORT)
				.show();
	}

	/**
	 * 控制菜单栏的显隐
	 */
	private void showMenuWindow() {
		if (mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		} else {
			mGridViewAdapter.getData(mMenuItemData1);
			mPopupWindow.showAtLocation(findViewById(R.id.RelativeLayout),
					Gravity.TOP, 0, 0);
		}
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) { // 截获菜单事件
		showMenuWindow();
		return false; // 返回为true 则显示系统menu
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("menu");// 必须创建一项
		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * 后台线程获取列表类
	 * 
	 * @author William
	 * 
	 */

	class BackgroundThread extends Thread {
		int flag;
		Handler getFileListHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				dlg_wait.dismiss();
			}
		};

		public BackgroundThread(int m) {
			flag = m;
		}

		public void run() {
			try {
				switch (flag) {
				case Varibles.GOOGLEDOCS:
					// DocsControl.getInstance(BrowserActivity.this)
					// .executeRefreshDocs();
					break;
				case Varibles.KANBOX:
					KanBoxControl.getInstance(BrowserActivity.this)
							.getFileList();
					break;
				case Varibles.VDISK:
					VDiskControl.getList(
							BrowserActivity.this,
							getSharedPreferences(Varibles.CONFIG_FILE,
									MODE_PRIVATE).getString(
									Varibles.VDISK_TOKEN, null));
					break;
				default:
					break;
				}
			} catch (Exception e) {
				// Toast.makeText(BrowserActivity.this, "程序错误",
				// Toast.LENGTH_SHORT)
				// .show();
				// finish();
			} finally {
				getFileListHandler.sendEmptyMessage(0);
			}
		}
	}// end thread
}
